﻿using Project.Net.Domain.Ex;
using System.Text.RegularExpressions;

namespace Project.Net.Domain.UserLogin
{
    public class User
    {
        public string Username { get; private set; }
        public string PasswordHash { get; private set; }
        public string Email { get; private set; }

        public int UserId { get; private set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="username"></param>
        /// <param name="passwordHash"></param>
        /// <param name="email"></param>
        public User(string username, string passwordHash, string email)
        {
            Username = username;
            PasswordHash = passwordHash;
            Email = email;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="username"></param>
        /// <param name="passwordHash"></param>
        /// <param name="email"></param>
        public User(string username, string passwordHash, string email, int userId)
        {
            Username = username;
            PasswordHash = passwordHash;
            Email = email;
            UserId = userId;
        }
        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="username"></param>
        /// <param name="passwordHash"></param>
        /// <param name="email"></param>
        /// <param name="passwordHasher"></param>
        /// <returns></returns>
        /// <exception cref="DomainException"></exception>
        public static User Create(string username, string passwordHash, string email,IPasswordHasher passwordHasher)
        {
             var emailRegexPattern = @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$";
            if (passwordHasher.IsTookWeak(passwordHash))
                throw new DomainException(CodeEnums.其他, "密码不安全，请重新设置密码！");
            if (string.IsNullOrWhiteSpace(email))
                throw new DomainException(CodeEnums.其他, "邮箱不能为空！");
            if (!Regex.IsMatch(email, emailRegexPattern))
                throw new DomainException(CodeEnums.其他, "请输入正确的邮箱！");
            return new User(username, passwordHasher.Hash(passwordHash), email);
        }

        /// <summary>
        /// 验证密码
        /// </summary>
        /// <param name="password"></param>
        /// <param name="passwordHasher"></param>
        /// <returns></returns>
        public bool VerifyPassword(string password, IPasswordHasher passwordHasher)
        {
            return passwordHasher.Verify(password, PasswordHash);
        }
    }
}
